package com.onairm.baselibrary.net;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.net.cache.db.CacheBeanDao;
import com.net.cache.db.DaoMaster;
import com.net.cache.db.DaoSession;
import com.onairm.baselibrary.Init;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by bqy on 2018/4/23.
 */

public class CacheManager {
    private static CacheManager manager;
    private final static String dbName = "cache_db";
    private DaoMaster.DevOpenHelper openHelper;
    private Context context;

    private CacheManager() {
        context = Init.context;
        openHelper = new DaoMaster.DevOpenHelper(context, dbName);
    }

    public static CacheManager getInstance() {
        if (manager == null) {
            synchronized (CacheManager.class) {
                if (manager == null) {
                    manager = new CacheManager();
                }
            }
        }
        return manager;
    }

    private SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    private SQLiteDatabase getWitableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    public void saveCache(CacheBean cacheBean) {
        DaoMaster daoMaster = new DaoMaster(getWitableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CacheBeanDao cacheBeanDao = daoSession.getCacheBeanDao();
        cacheBeanDao.insert(cacheBean);
    }

    public void updateCache(CacheBean cacheBean) {
        DaoMaster daoMaster = new DaoMaster(getWitableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CacheBeanDao cacheBeanDao = daoSession.getCacheBeanDao();
        cacheBeanDao.update(cacheBean);
    }

    public void deleteCache(CacheBean cacheBean) {
        DaoMaster daoMaster = new DaoMaster(getWitableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CacheBeanDao cacheBeanDao = daoSession.getCacheBeanDao();
        cacheBeanDao.delete(cacheBean);
    }

    public CacheBean queryCache(String key) {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CacheBeanDao cacheBeanDao = daoSession.getCacheBeanDao();
        QueryBuilder<CacheBean> qb = cacheBeanDao.queryBuilder();
        qb.where(CacheBeanDao.Properties.Key.eq(key));
        List<CacheBean> list = qb.list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }
}
